// src/main/java/com/miaostars/level/manager/DataSync.java
package com.miaostars.level.manager;

import com.miaostars.level.data.PlayerStats;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;

public class DataSync {
    private final JedisPool jedisPool; // Redis连接池
    private final DataSource dataSource; // MySQL连接池
    private final Map<UUID, PlayerStats> pendingSync = new ConcurrentHashMap<>();

    public DataSync(JedisPool jedisPool, DataSource dataSource) {
        this.jedisPool = jedisPool;
        this.dataSource = dataSource;
    }

    // Redis实时发布更新
    public void publishUpdate(UUID uuid, PlayerStats stats) {
        try (Jedis jedis = jedisPool.getResource()) {
            String channel = "miaostars_level";
            String message = uuid + ":" + stats.serialize();
            jedis.publish(channel, message);
        } catch (Exception e) {
            // 失败时暂存数据等待重试
            pendingSync.put(uuid, stats);
        }
    }

    // MySQL批量写入（每5分钟执行）
    public void startBatchSave() {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            if (pendingSync.isEmpty()) return;
            try (Connection conn = dataSource.getConnection()) {
                PreparedStatement ps = conn.prepareStatement(
                    "INSERT INTO player_stats VALUES (?,?,?,?) " +
                    "ON DUPLICATE KEY UPDATE kills=?, deaths=?, cps=?"
                );
                for (Map.Entry<UUID, PlayerStats> entry : pendingSync.entrySet()) {
                    PlayerStats stats = entry.getValue();
                    ps.setString(1, entry.getKey().toString());
                    ps.setInt(2, stats.getKills());
                    ps.setInt(3, stats.getDeaths());
                    ps.setDouble(4, stats.getCps());
                    ps.setInt(5, stats.getKills());
                    ps.setInt(6, stats.getDeaths());
                    ps.setDouble(7, stats.getCps());
                    ps.addBatch();
                }
                ps.executeBatch();
                pendingSync.clear();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }, 0, 5, TimeUnit.MINUTES); // 每5分钟执行
    }

    // 处理Redis订阅消息（跨服同步）
    public void subscribeUpdates() {
        new Thread(() -> {
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.subscribe(new JedisPubSub() {
                    @Override
                    public void onMessage(String channel, String message) {
                        String[] parts = message.split(":", 2);
                        UUID uuid = UUID.fromString(parts[0]);
                        PlayerStats stats = PlayerStats.deserialize(parts[1]);
                        // 更新本地缓存（例如：PlayerDataManager）
                    }
                }, "miaostars_level");
            }
        }).start();
    }
}